package com.lam.mall.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.common.components.file.service.FileService;
import com.lam.common.constant.CommonConstant;
import com.lam.common.constant.MallStateConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.utils.Arith;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;
import com.lam.mall.app.vo.ProductSimpleVo;
import com.lam.mall.app.vo.SearchProdVo;
import com.lam.mall.entity.ProdSku;
import com.lam.mall.entity.Product;
import com.lam.mall.mapper.ProductMapper;
import com.lam.mall.param.ProductParam;
import com.lam.mall.service.ProdSkuService;
import com.lam.mall.service.ProdTagRlService;
import com.lam.mall.service.ProductService;

/**
 * 商品管理Service业务层处理
 * 
 * @author admin
 * @date 2023-04-20
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
//    @Autowired
//    private AttachFileService attachFileService;
    @Autowired
    private ProdSkuService prodSkuService;
    @Autowired
    private ProdTagRlService prodTagRlService;
    @Autowired
    private ProductService productService;
    @Autowired
    private FileService fileService;

    /**
     * 查询商品管理
     * 
     * @param id ID
     * @return 单个对象
     */
//    @Cacheable(cacheNames = "productDetail", key = "#id")
    @Override
    @Transactional(readOnly = true)
    public Product selectById(String id, boolean withRelateData) {

    	Product prod = productMapper.selectById(id);
    	if(prod == null) {
    		throw new ParameterErrorException("查询数据有误！");
    	}
        if (!StringUtils.equals(prod.getShopId(), TokenUtils.getLoginUserShopId())) {
            throw new ParameterErrorException("您没有该数据的权限！");
        }
        prod.convertProperties(true);
        if(withRelateData) {
        	//商品SKU
            prod.setSkuList(prodSkuService.listByProdId(id));
            prod.getSkuList().stream().forEach(sku->sku.convertProperties(true));
            //获取分组标签
            prod.setTagList(prodTagRlService.listTagIdByProdId(id));
        }
        
        return prod;
    }
    
    @Override
    @Cacheable(cacheNames = "product", key = "#id")
    public Product getSampleProdByIdCache(String id) {
        return productMapper.selectById(id);
    }

    /**
     * 查询商品管理列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<Product> selectList(ProductParam param) {
    
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        //关键字查询
        if(StringUtils.isNotBlank(param.getKeywords())) {
            queryWrapper.and(wr->{
                wr.or().like("prod_name", param.getKeywords());
            });
        }
        queryWrapper.eq(StringUtils.isNotBlank(param.getShopId()), "shop_id", param.getShopId());
        queryWrapper.like(StringUtils.isNotBlank(param.getProdNameKey()), "prod_name", param.getProdNameKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getProdName()), "prod_name", param.getProdName());
        queryWrapper.eq(StringUtils.isNotBlank(param.getBrief()), "brief", param.getBrief());
        queryWrapper.eq(Objects.nonNull(param.getStatus()), "status", param.getStatus());
        queryWrapper.eq(Objects.nonNull(param.getCategoryId()), "category_id", param.getCategoryId());
        queryWrapper.ge(Objects.nonNull(param.getPutawayTimeBegin()), "putaway_time", param.getPutawayTimeBegin());
        queryWrapper.le(Objects.nonNull(param.getPutawayTimeEnd()), "putaway_time", param.getPutawayTimeEnd());
        
        queryWrapper.inSql(StringUtils.isNotBlank(param.getTagId()), "id", "select prod_id from mall_prod_tag_rl where prod_tag_id='"+param.getTagId()+"'");
        
        return productMapper.selectList(queryWrapper);
    }

    /**
     * 新增商品管理
     * 
     * @param product 
     * @return 
     */
    @Override
    @Transactional
    public int insert(Product product) {
    
    	product.setSoldNum(0);
    	productMapper.insert(product);
        if (CollectionUtil.isNotEmpty(product.getSkuList())) {
        	for (ProdSku sku : product.getSkuList()) {
        		sku.convertProperties(false);
        		sku.setProdId(product.getId());
        		sku.setDelStatus(CommonConstant.DEL_STATUS_NORMAL);
        		prodSkuService.insert(sku);
			}
        }
        prodTagRlService.insertBatch(product.getShopId(), product.getId(), product.getTagList());
        return 1;
    }

    /**
     * 修改商品管理
     * 
     * @param product 
     * @return 
     */
    @Caching(evict = {
            @CacheEvict(cacheNames = "product", key = "#product.id"),
            @CacheEvict(cacheNames = "productDetail", key = "#product.id"),
            @CacheEvict(cacheNames = "skuList", key = "#product.id")
    })
    @Override
    @Transactional
    public int update(Product product) {

    	Product dbProduct = productMapper.selectById(product.getId());
        if (!StringUtils.equals(dbProduct.getShopId(), TokenUtils.getLoginUserShopId())) {
        	throw new ParameterErrorException("您没有该数据的权限！");
        }
        if (!NumberUtil.eq(dbProduct.getStatus(), MallStateConstant.STATUS_ONLINE) 
        		&& NumberUtil.eq(product.getStatus(), MallStateConstant.STATUS_ONLINE)) {
            product.setPutawayTime(new Date());
        }
        productMapper.updateById(product);
    	//删除SKU
        prodSkuService.deleteByProdId(product.getId());
        //删除商品关联的分组标签
        prodTagRlService.deleteByProdId(product.getId());
        
        // 插入sku
        if (CollectionUtil.isNotEmpty(product.getSkuList())) {
        	for (ProdSku sku : product.getSkuList()) {
        		sku.convertProperties(false);
        		sku.setProdId(product.getId());
        		sku.setDelStatus(CommonConstant.DEL_STATUS_NORMAL);
        		prodSkuService.insert(sku);
			}
        }
        //插入商品关联的分组标签
        prodTagRlService.insertBatch(product.getShopId(), product.getId(), product.getTagList());
        
        fileService.updateUseFlagByFileName(product.getPic());
        for (String pic : product.getImgs().split(",")) {
        	fileService.updateUseFlagByFileName(pic);
		}
        
        return 1;
    }
    
    @Caching(evict = {
            @CacheEvict(cacheNames = "product", key = "#product.id"),
            @CacheEvict(cacheNames = "productDetail", key = "#product.id"),
            @CacheEvict(cacheNames = "skuList", key = "#product.id")
    })
    @Override
    @Transactional
    public int updateStatus(Product product) {

    	Product dbProduct = productMapper.selectById(product.getId());
        if (!StringUtils.equals(dbProduct.getShopId(), TokenUtils.getLoginUserShopId())) {
        	throw new ParameterErrorException("您没有该数据的权限！");
        }
        
        Product newProduct = new Product();
        newProduct.setId(product.getId());
        newProduct.setStatus(product.getStatus());
        if (!NumberUtil.eq(dbProduct.getStatus(), MallStateConstant.STATUS_ONLINE) 
        		&& NumberUtil.eq(product.getStatus(), MallStateConstant.STATUS_ONLINE)) {
        	newProduct.setPutawayTime(new Date());
        	newProduct.setUpdateTime(new Date());
        }
        productMapper.updateById(newProduct);
        return 1;
    }
    
    @Caching(evict = {
            @CacheEvict(cacheNames = "product", key = "#id"),
            @CacheEvict(cacheNames = "productDetail", key = "#id"),
            @CacheEvict(cacheNames = "skuList", key = "#id")
    })
    @Override
    @Transactional
    public int deleteById(String id){
    	String shopId = TokenUtils.getLoginUserShopId();
    	Product prod = productMapper.selectById(id);
    	if(prod == null) {
    		throw new ParameterErrorException("查询数据有误！");
    	}
        if (!StringUtils.equals(prod.getShopId(), shopId)) {
            throw new ParameterErrorException("您没有该数据的权限！");
        }
        
        // 删除商品
        productMapper.logicDeleteById(id);
        //删除SKU
        prodSkuService.logicDeleteByProdId(id);
        //删除商品关联的分组标签
        prodTagRlService.deleteByProdId(id);

        // 删除数据库中的商品图片
//        if (StrUtil.isNotBlank(dbProduct.getImgs())) {
//            String[] imgs = dbProduct.getImgs().split(StrUtil.COMMA);
//            for (String img : imgs) {
//                attachFileService.deleteFile(img);
//            }
//        }
        return 1;
    }

    /**
     * 删除商品管理信息
     * 
     * @param idStr ID，多个用逗号分隔
     * @return 
     */
    @Override
    @Transactional
    public int deleteByIds(List<String> idList) {
    
        if(CollectionUtil.isEmpty(idList)) {
            return 0;
        }
        
        for (String id : idList) {
        	productService.deleteById(id);
		}
        return 1;
    }
    
    @Caching(evict = {
            @CacheEvict(cacheNames = "product", key = "#id"),
            @CacheEvict(cacheNames = "productDetail", key = "#id"),
            @CacheEvict(cacheNames = "skuList", key = "#id")
    })
    @Override
    public void removeProductCacheById(String id) {
    }

	@Override
	public List<ProductSimpleVo> pageByPutAwayTime() {
		return productMapper.pageByPutAwayTime();
	}
    
	@Override
    public List<ProductSimpleVo> pageByTagId(String tagId) {
        return productMapper.pageByTagId(tagId);
    }
	
	@Override
    public List<ProductSimpleVo> moreBuyProdList() {
        return productMapper.moreBuyProdList();
    }
	
//	@Override
//    public List<TagProductVo> tagProdList() {
//        return productMapper.tagProdList();
//    }
	
	@Override
    public List<ProductSimpleVo> pageByCategoryId(String categoryId) {
        return productMapper.pageByCategoryId(categoryId);
    }
	
	@Override
    public List<SearchProdVo> getSearchProdPageByProdName(String prodName, Integer sort, Integer orderBy) {
        List<SearchProdVo> list = productMapper.getSearchProdPageByProdName( prodName, sort, orderBy);
        for (SearchProdVo searchProdVo : list) {
            //计算出好评率
            if (searchProdVo.getPraiseNumber() == 0 || searchProdVo.getProdCommNumber() == 0) {
                searchProdVo.setPositiveRating(0.0);
            } else {
                searchProdVo.setPositiveRating(Arith.mul(Arith.div(searchProdVo.getPraiseNumber(), searchProdVo.getProdCommNumber()), 100));
            }
        }
        return list;
    }
	
	@Override
    public List<ProductSimpleVo> collectionProds(String userId) {
        return productMapper.collectionProds(userId);
    }
	
	@Override
	public List<ProductSimpleVo> browseProds(String userId) {
		return productMapper.browseProds(userId);
	}

}
